package com.hiwan.unions.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.hiwan.unions.R;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.application.MyApplication;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by haorui on 2016/8/4.
 */
public class SystemUtil {
    private static final int[] APPCOMPAT_CHECK_ATTRS = {R.attr.colorPrimary};

    /**
     * 检查WIFI是否连接
     */
    public static boolean isWifiConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return wifiInfo != null;
    }

    /**
     * 检查手机网络(4G/3G/2G)是否连接
     */
    public static boolean isMobileNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileNetworkInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return mobileNetworkInfo != null;
    }

    /**
     * 检查是否有可用网络
     */
    public static boolean isNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        return connectivityManager.getActiveNetworkInfo() != null;
    }

//    /**
//     * 保存图片到本地
//     * @param context
//     * @param url
//     * @param bitmap
//     */
//    public static Uri saveBitmapToFile(Context context, String url, Bitmap bitmap,View container, boolean isShare){
//        String fileName = url.substring(url.lastIndexOf("/"),url.lastIndexOf(".")) + ".png";
//        File fileDir = new File(Constants.PATH_DATA);
//        if (!fileDir.exists()){
//            fileDir.mkdir();
//        }
//        File imageFile = new File(fileDir,fileName);
//        Uri uri = Uri.fromFile(imageFile);
//        if (isShare && imageFile.exists()) {
//            return uri;
//        }
//        try {
//            FileOutputStream fos = new FileOutputStream(imageFile);
//            boolean isCompress = bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
//            if (isCompress) {
//                SnackbarUtil.showShort(container,"保存妹纸成功n(*≧▽≦*)n");
//            } else {
//                SnackbarUtil.showShort(container,"保存妹纸失败ヽ(≧Д≦)ノ");
//            }
//            fos.flush();
//            fos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//            SnackbarUtil.showShort(container,"保存妹纸失败ヽ(≧Д≦)ノ");
//        }
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(), imageFile.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));
//        return uri;
//    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int dp2px(float dpValue) {
        final float scale = MyApplication.getInstance().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2dp(float pxValue) {
        final float scale = MyApplication.getInstance().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static void checkAppCompatTheme(Context context) {
        TypedArray a = context.obtainStyledAttributes(APPCOMPAT_CHECK_ATTRS);
        final boolean failed = !a.hasValue(0);
        if (a != null) {
            a.recycle();
        }
        if (failed) {
            throw new IllegalArgumentException("You need to use a Theme.AppCompat theme "
                    + "(or descendant) with the design library.");
        }
    }


    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 获取手机 imei号码
     */
    public static String getImei(Context context) {
        SharedPreferences userInfoC = context.getSharedPreferences(ConstantsValues.APP,
                Context.MODE_PRIVATE);
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (imei.equals("")) {
                return userInfoC.getString(ConstantsValues.IMECODE, "123123");
            } else {
                return tm.getDeviceId();
            }
        } catch (RuntimeException e) {
            return userInfoC.getString(ConstantsValues.IMECODE, "123123");
        }
    }

}
